<template>
  <el-container style="padding: 24px">
    <el-aside style="width: 18%;">
      <el-card class="treeCard" style="height: 220px;">
        <el-scrollbar style="height: 180px;">
          <el-row>
            <el-tree
              class="flow-tree"
              :props="mainProps"
              :load="loadNode"
              node-key="uri"
              ref="tree"
              :highlight-current="true"
              lazy
              @node-click="handleNodeClick"
              show-checkbox
            >
            </el-tree>
          </el-row>
          <el-row style="margin-top: 2%">
            <el-button style="float: right" type="primary" @click="registerModels">注册模型</el-button>
          </el-row>
        </el-scrollbar>
      </el-card>
      <el-row>
        <el-card class="calCard" style="height: 566px">
          <!--            <el-tab-pane label="效率计算" name="first">-->
          <!--              <el-form-->
          <!--                :model="efficiencyForm"-->
          <!--                :rules="efficiencyFormRules"-->
          <!--                ref="efficiencyForm"-->
          <!--                label-position="left"-->
          <!--                label-width="160px"-->
          <!--              >-->
          <!--                <el-form-item label="模型id">-->
          <!--                  <el-select v-model="effFormModelId" clearable placeholder="请选择模型id">-->
          <!--                    <el-option-->
          <!--                      v-for="item in effFormModelIdOptions"-->
          <!--                      :label="item.label"-->
          <!--                      :value="item.value"-->
          <!--                      :key="item.value"-->
          <!--                    ></el-option>-->
          <!--                  </el-select>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="气体不完全燃烧损失">-->
          <!--                  <el-input-->
          <!--                    v-model="efficiencyForm.gas_burn_loss"-->
          <!--                    placeholder="默认 0.3"-->
          <!--                  ></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="固体不完全燃烧损失">-->
          <!--                  <el-input v-model="efficiencyForm.solid_burn_loss" placeholder="默认 2.5"></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="散热损失">-->
          <!--                  <el-input v-model="efficiencyForm.heat_loss" placeholder="默认 1"></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="灰渣热损失">-->
          <!--                  <el-input v-model="efficiencyForm.ash_heat_loss" placeholder="默认 0.232"></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="冷空气理论热焓">-->
          <!--                  <el-input v-model="efficiencyForm.air_theory_enthalpy" placeholder="默认 177.534"></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-form-item label="低位发热量">-->
          <!--                  <el-input v-model="efficiencyForm.low_calorific_value" placeholder="默认 17556.091"></el-input>-->
          <!--                </el-form-item>-->
          <!--                <el-row>-->
          <!--                  <el-col :span="12">-->
          <!--                    <span>计算的实时效率:</span>-->
          <!--                    <span>{{this.calEff}}</span>-->
          <!--                  </el-col>-->
          <!--                  <el-col :span="12">-->
          <!--                    <el-button-->
          <!--                      @click="calEfficiency()"-->
          <!--                      type="primary"-->
          <!--                      style=" ">提交-->
          <!--                    </el-button>-->
          <!--                  </el-col>-->
          <!--                </el-row>-->
          <!--              </el-form>-->

          <!--            </el-tab-pane>-->
          <el-header style="margin-left: -70%">
            <h4>优化主调参数</h4>
          </el-header>
          <el-form
            :model="optMainParams"
            :rules="optMainParamsRules"
            ref="optMainParams"
            label-position="right"
            label-width="80px"
          >
            <el-form-item label="模型id" style="">
              <el-select v-model="effFormModelId" clearable placeholder="请选择模型id">
                <el-option
                  v-for="item in effFormModelIdOptions"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供浆流量1">
              <el-input v-model="optMainParams.supplyFlow1" placeholder="2000-2400"></el-input>
            </el-form-item>
            <el-form-item label="供浆流量2">
              <el-input v-model="optMainParams.supplyFlow2" placeholder="2000-2400"></el-input>
            </el-form-item>
            <el-form-item label="鼓风风量">
              <el-input v-model="optMainParams.airVolume" placeholder="16000-20000"></el-input>
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <span style="float: left">计算的优化效率:{{this.ownOptEff}}</span>
              </el-col>
              <el-col :span="12">
                <el-button @click="getOptEfficiency(optMainParams,'optMainParams')"
                           type="primary"
                           style="">
                  确认
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-row>
      <el-row>
      </el-row>
    </el-aside>
    <el-container class="middleContainer" direction="vertical" style="width: 50%">
      <!--        模型训练-->
      <el-card class="modelCard" style="height: 220px;">

        <!--          <el-row :gutter="10" style="margin-bottom: 2%">-->
        <!--            <el-col :span="6">-->
        <!--              <el-select v-model="projectSelection" clearable placeholder="请选择" size="mini"-->
        <!--                         @change="projectSelectionChange" @clear="clearProjectSelection">-->
        <!--                <el-option-->
        <!--                  v-for="item in projectSelectionOptions"-->
        <!--                  :key="item.projectId"-->
        <!--                  :label="item.projectName"-->
        <!--                  :value="item.projectId">-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--            </el-col>-->
        <!--            <el-col :span="6">-->
        <!--              <el-select v-model="boilersSelection" :disabled="projectSelection===''"-->
        <!--                         clearable placeholder="请选择" @change="selectionChange"-->
        <!--                         @clear="selectionChange">-->
        <!--                <el-option-->
        <!--                  v-for="item in boilersSelectionOptions"-->
        <!--                  :key="item.boilerId"-->
        <!--                  :label="item.boilerName"-->
        <!--                  :value="item.boilerId">-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--            </el-col>-->
        <!--            <el-col :span="6">-->
        <!--              <el-select v-model="parasSelection" clearable placeholder="请选择"-->
        <!--                         @change="selectionChange"-->
        <!--                         @clear="selectionChange">-->
        <!--                <el-option-->
        <!--                  v-for="item in parasSelectionOptions"-->
        <!--                  :key="item.paraId"-->
        <!--                  :label="item.paraName"-->
        <!--                  :value="item.paraId">-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--            </el-col>-->
        <!--            <el-col :span="6">-->
        <!--              <el-button type="primary" round @click="optimization" class=button-style autofocus>一 键 优 化</el-button>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <el-row>
          <el-table
            :header-cell-style="GLOBAL.elHeaderStyle"
            :border="true"
            :data="optModelData"
            style="font-size: 13.5px;width: 100%;"
            height="280"
          >
            <el-table-column
              fixed="left"
              prop="modelId" label="模型id" align="left" width="60px"></el-table-column>
            <el-table-column prop="projectName" label="项目名称" align="left"></el-table-column>
            <el-table-column prop="boilerName" label="锅炉名称" align="left"></el-table-column>
            <el-table-column prop="optNumber" label="优化量" align="left"></el-table-column>

            <el-table-column prop="trainingState" label="训练状态" align="left">
              <template v-slot="{row}">
                <el-switch v-model="row.trainingState" :disabled="row.trainingState" @change="trainModel(row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="onLineState" label="上线状态" align="left">
              <template v-slot="{row}">
                <el-switch v-model="row.onLineState" :disabled="row.trainingState" @change="onLineModel(row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              prop="opt" label="优化" align="left">
              <template v-slot="{row}">
                <el-button @click="optimization(row)" type="primary">优化</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-card>
      <!--得分环-->
      <!--        <el-card class="ring-outer" style="height: 300px">-->
      <el-card class="ring-outer" style="height: 200px">
        <RingGaugeChart
          :chartTitle="'各效率展示'"
          :before-value="beforeOptimize"
          :current-value="currentOptimize"
          :target-value="targetOptimize"
        ></RingGaugeChart>
      </el-card>
      <el-card class="bar-outer" style="height:350px">
        <el-row>
          <el-table
            :data="calEffTableData"
            :header-cell-style="GLOBAL.elHeaderStyle"
            :border="true"
            style="font-size: 13.5px;width: 100%;"

          >
            <el-table-column label="效率" prop="name" width="50px"></el-table-column>
            <el-table-column label="模型id" width="100px" prop="model_id">
              <template v-slot="{row}">
                <el-select v-model="row.model_id">
                  <el-option
                    v-for="item in effFormModelIdOptions"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="气体不完全燃烧损失" prop="gas_burn_loss" width="100px">
              <template v-slot="{row}">
                <el-input v-model="row.gas_burn_loss"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="固体不完全燃烧损失" prop="solid_burn_loss" width="100px">
              <template v-slot="{row}">
                <el-input v-model="row.solid_burn_loss"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="散热损失" prop="heat_loss" width="100px">
              <template v-slot="{row}">
                <el-input v-model="row.heat_loss"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="灰渣热损失" prop="ash_heat_loss" width="100px">
              <template v-slot="{row}">
                <el-input v-model="row.ash_heat_loss"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="冷空气理论热焓" prop="air_theory_enthalpy" width="100px">
              <template v-slot="{row}">
                <el-input v-model="row.air_theory_enthalpy"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="低位发热量" prop="low_calorific_value" width="110px">
              <template v-slot="{row}">
                <el-input v-model="row.low_calorific_value"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              prop="opt"
              align="left"
              width="50px"
            >
              <template v-slot="{row}">
                <el-button
                  @click="calEfficiency(row)"
                  type="text"
                  v-show="row.name!=='实际'"
                >编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row style="margin-top: 1%">
          <div style="float: right">
            <span>设计的优化效率：{{this.calEff}}</span>
          </div>
        </el-row>
        <!--        <el-form-->
        <!--          :model="efficiencyForm"-->
        <!--          :rules="efficiencyFormRules"-->
        <!--          ref="efficiencyForm"-->
        <!--          label-position="left"-->
        <!--          label-width="160px"-->
        <!--        >-->
        <!--          <el-form-item label="模型id">-->
        <!--            <el-select v-model="effFormModelId" clearable placeholder="请选择模型id">-->
        <!--              <el-option-->
        <!--                v-for="item in effFormModelIdOptions"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--                :key="item.value"-->
        <!--              ></el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="气体不完全燃烧损失">-->
        <!--            <el-input-->
        <!--              v-model="efficiencyForm.gas_burn_loss"-->
        <!--              placeholder="默认 0.3"-->
        <!--            ></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="固体不完全燃烧损失">-->
        <!--            <el-input v-model="efficiencyForm.solid_burn_loss" placeholder="默认 2.5"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="散热损失">-->
        <!--            <el-input v-model="efficiencyForm.heat_loss" placeholder="默认 1"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="灰渣热损失">-->
        <!--            <el-input v-model="efficiencyForm.ash_heat_loss" placeholder="默认 0.232"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="冷空气理论热焓">-->
        <!--            <el-input v-model="efficiencyForm.air_theory_enthalpy" placeholder="默认 177.534"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="低位发热量">-->
        <!--            <el-input v-model="efficiencyForm.low_calorific_value" placeholder="默认 17556.091"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-row>-->
        <!--            <el-col :span="12">-->
        <!--              <span>计算的实时效率:</span>-->
        <!--              <span>{{this.calEff}}</span>-->
        <!--            </el-col>-->
        <!--            <el-col :span="12">-->
        <!--              <el-button-->
        <!--                @click="calEfficiency()"-->
        <!--                type="primary"-->
        <!--                style=" ">提交-->
        <!--              </el-button>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-form>-->
      </el-card>
    </el-container>
    <el-container class="rightContainer" direction="vertical" style="width: 50%">
      <el-card class="preCard" style="height: 436px;">
        <el-empty description="未优化" v-if="!optimized"></el-empty>
        <el-tabs v-model="activeChartName" style="width: 100%" v-if="optimized">
          <el-tab-pane label="柱状图" name="bar" lazy>
            <BarChart
              ref="bar"
              :id="chartModelId"
              :key="chartModelId"
              :chart-title="'主调参数优化目标'"
              :control-aim="controlAim"
              :control-para-name="controlParaName"
              :control-uri="controlUri"
            ></BarChart>
          </el-tab-pane>
          <el-tab-pane label="雷达图" name="radar" lazy>
            <RadarChart
              ref="radar"
              :id="chartModelId"
              :key="chartModelId"
              :chartTitle="'优化目标参数雷达图'"
              :control-aim="controlAim"
              :control-para-name="controlParaName"
              :control-uri="controlUri"
            >
            </RadarChart>
          </el-tab-pane>
        </el-tabs>
        <!--        <el-empty description="未选择优化种类" v-if="currentParams.length===0"></el-empty>-->
        <!--        <el-scrollbar style="height: 435px">-->
        <!--          &lt;!&ndash;          <el-card style="height: 800px;">&ndash;&gt;-->
        <!--          <div>-->
        <!--            <el-row>-->
        <!--              <el-col :span="6" v-for="(currentParam,index) in this.currentParams" :key="index">-->
        <!--                <el-card style="height: 100px;" shadow="hover" @click.native="handleParamClick(currentParam)">-->
        <!--                  <div slot="header" style="height: 12px;line-height: 12px">-->
        <!--                    <el-row>-->
        <!--                      <span style="font-weight: bold;font-size:12px;margin-left: -5px;">{{currentParam.optimizationGoals}}</span>-->
        <!--                    </el-row>-->
        <!--                  </div>-->
        <!--                  <el-row style="height: 12px;">-->
        <!--                    <div>-->
        <!--                      <span style="font-size: 18px;color: darkgray;line-height: 18px">{{twoNumber(currentParam.currentValue)}}{{currentParam.unit}}</span>-->
        <!--                    </div>-->
        <!--                  </el-row>-->
        <!--                </el-card>-->
        <!--              </el-col>-->
        <!--            </el-row>-->
        <!--          </div>-->
        <!--        </el-scrollbar>-->
      </el-card>
      <el-card class="line-outer" style="height:350px">
        <EffChart
          @currentEffValue="parentFn"
          :id="'eff'"
          :uri="writeBackUri"
          :chargeUri="boilerChargeUri"
          :transTarget="transTarget"
        ></EffChart>
      </el-card>
    </el-container>
  </el-container>

</template>

<script>
  import {getNodesByBrowsePath, register, queryHistoryRawValueByUri} from "../../api/faultWarning";
  import {
    getCurrentEfficiency,
    getOptimalEfficiency,
    queryCurrentRawValueByUri,
    getOptModelsInfo,
    getEfficiency,
    train,
    getOwnOptimalEfficiency,
    registerOptModel,
    onlineEfficiency
  } from "../../api/effopt";
  import BarChart from "../../components/optimization/BarChart";
  import RadarChart from "../../components/optimization/RadarChart";
  import LineChart from "../../components/optimization/LineChart";
  import RingGaugeChart from "../../components/optimization/RingGaugeChart";
  import EffChart from "../../components/optimization/EffChart"
  import * as echarts from "echarts";

  export default {
    name: "NewEffOpt",
    components: {BarChart, RadarChart, LineChart, RingGaugeChart, EffChart},
    data() {
      return {
        //************************
        //*********判断锅炉是否在运行***********
        //************************
        boilerStateUri: [],
        boilerState: [],

        //************************
        //*********树相关***********
        //************************
        //获取令牌
        client_id: '',
        client_secret: '',
        grant_type: '',
        requestToken: '',
        getNodeToken: '',
        getNodeParam: '',
        //树
        mainProps: {
          children: 'children',
          label: 'name',
          isLeaf(data, node) {
            return node.level === 4;
          }
        },
        //点击树节点使用的量
        getTableNodeParam: '',
        namesForSecondTable: [],
        urisForSecondTable: [],
        unitForSecondTable: [],

        //显示控制
        optimized: false,
        activeName: "first",

        //************************
        //*******环状图相关***********
        //************************
        //环状图
        circle1: false,
        circle2: false,
        circle3: false,

        beforeOptimize: 0.00,
        currentOptimize: 0.00,
        targetOptimize: 0.00,
        targetOptimizeArray: [],
        transTarget: [],
        //************************
        //*******柱状图相关***********
        //************************
        activeChartName: 'bar',
        controlParas: {},
        mainControl: [],
        controlUri: [],
        chartModelId: 0,
        // optNum: 5,
        // optEfficiency: 2,

        //************************
        //*******雷达图相关***********
        //************************
        // 雷达图
        controlAim: [],
        controlCurrent: [],
        controlParaName: [],
        optimal: 0,

        //************************
        //*******右侧表格相关***********
        //************************
        currentRowUri: null,
        afterOptTableData: [],
        valueShow: false,
        stateShow: false,
        image: '',
        currentParams: [],
        defaultPreUri: '',

        //************************
        //*****优化模型表相关********
        //************************
        optModelData: [],
        projectSelection: '',
        projectSelectionOptions: [],
        boilersSelection: '',
        boilersSelectionOptions: [],
        parasSelection: '',
        parasSelectionOptions: [],
        realParamData: [],
        totalSize: 0,
        pageSize: 5,
        pageNum: 1,
        currentPage: 1,

        //************************
        //*****效率计算表单相关********
        //************************
        calEffTableData: [{
          name: '实际',
          model_id: '',
          gas_burn_loss: 0.3,
          solid_burn_loss: 2.5,
          heat_loss: 1,
          ash_heat_loss: 0.232,
          air_theory_enthalpy: 177.534,
          low_calorific_value: 17556.091
        },
          {
            name: '设计',
            model_id: '',
            gas_burn_loss: 0.3,
            solid_burn_loss: 2.5,
            heat_loss: 1,
            ash_heat_loss: 0.232,
            air_theory_enthalpy: 177.534,
            low_calorific_value: 17556.091
          }],
        efficiencyForm: {
          gas_burn_loss: 0.3,
          solid_burn_loss: 2.5,
          heat_loss: 1,
          ash_heat_loss: 0.232,
          air_theory_enthalpy: 177.534,
          low_calorific_value: 17556.091
        },
        designEfficiencyForm: {
          gas_burn_loss: 0.3,
          solid_burn_loss: 2.5,
          heat_loss: 1,
          ash_heat_loss: 0.232,
          air_theory_enthalpy: 177.534,
          low_calorific_value: 17556.091
        },
        designEffFormModelId: '',
        effFormModelIdOptions: [
          {
            value: '',
            label: ''
          }
        ],
        effFormModelId: '',
        efficiencyFormRules: {
          gasBurnLoss: [
            {required: true, message: '请输入数字', trigger: 'blur'}
          ],
          solidBurnLoss: [{required: true, message: '请输入数字', trigger: 'blur'}],
          heatLoss: [{required: true, message: '请输入数字', trigger: 'blur'}],
          ashHeatLoss: [{required: true, message: '请输入数字', trigger: 'blur'}],
          airTheoryEnthalpy: [{required: true, message: '请输入数字', trigger: 'blur'}],
          lowCalorificValue: [{required: true, message: '请输入数字', trigger: 'blur'}]
        },
        calEff: 0,

        //************************
        //*****优化主调参数相关********
        //************************
        optMainParams: {
          supplyFlow1: '',
          supplyFlow2: '',
          airVolume: ''
        },
        ownOptEff: 0,
        optMainParamsRules: {
          supplyFlow1: [
            {required: true, message: '请输入数字', trigger: 'blur'},

          ],
          supplyFlow2: [{required: true, message: '请输入数字', trigger: 'blur'}],
          airVolume: [{required: true, message: '请输入数字', trigger: 'blur'}]
        },

        //************************
        //*****右侧效率曲线相关********
        //************************
        effData: [],
        selectedRowUri: '',
        selectedRowName: '',
        writeBackUri: '',
        timeInterval: 300000,
        realCurrentEffTime: [],
        realCurrentEffValue: [],
        effChartData: [],
        boilerChargeUri: ''

      }
    },
    async mounted() {
      document.documentElement.scrollTop = 0;
      //锅炉运行状态uri(分别是1,2,3号)
      this.boilerStateUri =
        [
          "/Project_XCYW/72be3a8b-c7ad-4d96-8a69-ff4c84c220b1",
          "/Project_XCYW/68918245-9202-4a51-82a3-4db09f88091c",
          "/Project_XCYW/f9e5d2d9-2c03-4f90-bb6f-7eb24f57b0b0"
        ];


      //初始化页面时获取用户令牌以及树节点
      this.client_id = "GLYFX";
      this.client_secret = "9ddfd71b-1afe-11a2-9321-b03c30700485";
      this.grant_type = "client_credentials";
      await this.UserRegister();
      this.LoadModels();
      // this.intervalGetEff();
    },
    beforeDestroy() {
      // console.log("clearInterval");
      clearInterval(this.currentInternal);

    },
    methods: {
      /**
       *显示两位小数
       */
      twoNumber(val) {
        return val.toFixed(2);
      },

      /**
       * 查询锅炉工作状态
       *
       */
      getBoilerState() {
        queryCurrentRawValueByUri(this.boilerStateUri).then((res) => {
          if (res) {
            for (let i = 0; i < res.data.result.length; i++) {
              this.boilerState.push(res.data.result[i].v)
            }
          }
        })
      },

      /**
       * 树相关
       * @constructor
       */
      //获取用户令牌
      async UserRegister() {
        //获取锅炉工作状态
        this.getBoilerState();
        const params = new URLSearchParams({
          client_id: this.client_id,
          client_secret: this.client_secret,
          grant_type: this.grant_type
        });
        await register(params).then((res) => {
          if (res) {
            //存放令牌
            this.requestToken = res.data.token_type + " " + res.data.access_token;
          }
          //console.log("令牌：" + this.requestToken);
          //拿到令牌后通过客户端模式访问资源
          this.getNodeToken = this.requestToken;//(token)
        });


      },

      //懒加载
      loadNode(node, resolve) {
        this.node = node;

        if (node.level === 0) {
          return resolve([{name: "优化运行", uri: "root"}]);
        }

        if (node.level === 1) {
          this.getNodeParam = JSON.stringify({
            "depth": 1,
            "forward": true,
            "id": "6122e02dba3fd029798b2ebe"
          });
        } else if (node.level === 4) {
          return resolve([])
        } else {
          this.getNodeParam = {
            "depth": 1,
            "forward": true,
            "id": node.data.uri.split("/")[2]
          };

        }
        //获取树节点并按拼音首字母排序
        getNodesByBrowsePath(this.getNodeToken, this.getNodeParam).then((res) => {
          if (res) {

            let tmp = res.data.result[0];
            tmp.children = tmp.children.filter(function (item) {
              return item.uri.substring(0, 8) === '/Project'
            }).sort((a, b) => a.name.localeCompare(b.name, 'en'));

            return resolve(tmp.children);
          }
        });
      },

      /**
       * 初始化页面加载锅炉的关键参数
       */
      getPresent() {

        // console.log('this.defaultPreUri', this.defaultPreUri);
        let tmpGetTableNodeParam = {
          "depth": 1,
          "forward": true,
          "id": this.defaultPreUri
        };

        getNodesByBrowsePath(this.getNodeToken, tmpGetTableNodeParam).then((res) => {
          this.namesForSecondTable = [];
          this.urisForSecondTable = [];
          this.unitForSecondTable = [];
          if (res) {
            let tmp = res.data.result[0];
            let filterNodes = tmp.children.filter(function (item) {
              return item.uri.substring(0, 8) === '/Project'
            });
            //名称，uri，单位
            for (let i = 0; i < filterNodes.length; i++) {
              let nodeName = '';
              nodeName = filterNodes[i].name;
              if (nodeName.indexOf("关键") === -1 && nodeName.indexOf("效率") === -1) {
                this.namesForSecondTable.push(nodeName);
                this.urisForSecondTable.push(filterNodes[i].uri);
                let unit = '';
                if (nodeName.indexOf("流量") !== -1) {
                  unit = 'kg/h';
                } else if (nodeName.indexOf("电流") !== -1) {
                  unit = 'A';
                } else if (nodeName.indexOf("压力") !== -1) {
                  unit = 'MPa';
                } else if (nodeName.indexOf("温度") !== -1) {
                  unit = '℃';
                } else if (nodeName.indexOf("负压") !== -1) {
                  unit = 'Pa';
                } else if (nodeName.indexOf("氧量") !== -1) {
                  unit = '%';
                } else if (nodeName.indexOf("风量") !== -1) {
                  unit = 'm3/h';
                } else {
                  unit = '单位未知';
                }
                this.unitForSecondTable.push(unit);
              }
            }
            this.intervalTasks();
            this.intervalId = setInterval(this.intervalTasks, 2000);
          }
        })
      },
      /**
       * 确定按钮，生成并训练选中节点的模型
       */
      async registerModels() {
        let tree = this.$refs.tree;
        // console.log('tree', tree);
        for (let key of tree.getCheckedKeys()) {
          let node = tree.getNode(key);
          if (node.level === 4) {
            await this.registerNode(node);
          }
        }
      },

      /**
       */
      click(node) {

      },
      /**
       * 注册节点
       */
      async registerNode(node) {
        let tree = this.$refs.tree;
        // console.log('树节点', node);
        node.data.disabled = true;
        tree.setChecked(node.data, false, false);
        let parentNode = node.parent;
        let boilerName = parentNode.data.name;
        let projectName = parentNode.parent.data.name;
        let paraName = node.data.name;
        let nodeParam = {
          "depth": 2,
          "forward": true,
          "id": node.data.uri.split("/")[2]
        };

        await getNodesByBrowsePath(this.getNodeToken, nodeParam).then((res) => {
          if (res) {
            let nodes = res.data.result[0].children;
            let nodesDict = {};
            for (let item of nodes) {
              nodesDict[item.name] = item;
            }
            let writeBack = {
              currentEfficiency: nodesDict["实时效率"].uri + "/" + nodesDict["实时效率"].properties.BrowseName,
              optEfficiency: nodesDict["优化效率"].uri + "/" + nodesDict["优化效率"].properties.BrowseName
            };
            console.log('writeBack', writeBack);
            let children = nodesDict["关键参数"].children;
            let uris = [];
            for (let i = 0; i < children.length; i++) {
              let uri = children[i].uri;
              if (uri.substring(0, 8) !== '/Project') {
                continue
              }
              let element = {
                name: children[i].name,
                uri
              };
              uris.push(element)
            }

            let param = {
              "node_uri": node.data.uri,
              "write_back": writeBack,
              "uris": uris,
              "window_size": 300000,
              "project_name": projectName,
              "boiler_name": boilerName,
              "para_name": paraName
            };
            // console.log("Registerparam",param);
            registerOptModel(param).then((res) => {
              if (res) {
                // console.log(res.data)
              }
            })
          }
        });
      },

      /**
       * 上线
       */
      onLineModel(row) {
        let model_id = '';
        model_id = row.modelId;
        let state = row.onLineState;
        let param = {
          "model_id": model_id,
          "to_online": state
        };
        // console.log(param);
        onlineEfficiency(param).then((res) => {
          if (res) {
            // console.log('上线res', res);
          }
        });

      },

      refreshTable() {
        /**
         * 调用api，参数model_id,查询该id的模型清单
         * 表格刷新elmentui有方法（结合刚才说的模型优化的代码流程，考虑状态数据怎么拿回来）
         *
         */
      },
      handleNodeClick1(data) {
        /**
         * 1.点击刷新右侧仪表盘
         * 2.点击刷新中部模型列表(调用表格刷新方法)refreshTable()
         * 3.判断当前节点是否为锅炉节点，如果是锅炉节点那么遍历它的孩子节点，一级，
         * 然后把当前子节点循环遍历之前代码
         * 4.
         */


      },
      handleNodeClick(data) {

        this.valueShow = false;
        this.stateShow = false;
        this.beforeOptimize = 0.00;
        this.targetOptimize = 0.00;
        this.optimized = false;

        this.showMiddleCard = true;
        this.showRightCard = true;
        this.getTableNodeParam = {
          "depth": 2,
          "forward": true,
          "id": data.uri.split("/")[2]
        };
        getNodesByBrowsePath(this.getNodeToken, this.getTableNodeParam).then((res) => {
          this.namesForSecondTable = [];
          this.urisForSecondTable = [];
          this.unitForSecondTable = [];

          if (res) {
            let nodes = res.data.result[0].children;
            let nodesDict = {};
            for (let item of nodes) {
              nodesDict[item.name] = item;
            }
            let children = nodesDict["关键参数"].children;
            let filterNodes = children.filter(function (item) {
              return item.uri.substring(0, 8) === '/Project'
            });
            //名称，uri，单位
            for (let i = 0; i < filterNodes.length; i++) {
              let nodeName = '';
              nodeName = filterNodes[i].name;
              if (nodeName.indexOf("关键") === -1 && nodeName.indexOf("效率") === -1) {
                this.namesForSecondTable.push(nodeName);
                this.urisForSecondTable.push(filterNodes[i].uri);
                let unit = '';
                if (nodeName.indexOf("流量") !== -1) {
                  unit = 'kg/h';
                } else if (nodeName.indexOf("电流") !== -1) {
                  unit = 'A';
                } else if (nodeName.indexOf("压力") !== -1) {
                  unit = 'MPa';
                } else if (nodeName.indexOf("温度") !== -1) {
                  unit = '℃';
                } else if (nodeName.indexOf("负压") !== -1) {
                  unit = 'Pa';
                } else if (nodeName.indexOf("氧量") !== -1) {
                  unit = '%';
                } else if (nodeName.indexOf("风量") !== -1) {
                  unit = 'm3/h';
                } else {
                  unit = '单位未知';
                }
                this.unitForSecondTable.push(unit);
              }
            }
            this.intervalTasks();
            this.intervalId = setInterval(this.intervalTasks, 2000);
          }
        });
      },

      intervalTasks() {
        this.drawfData();

        let uris = [];
        for (let i = 0; i < this.namesForSecondTable.length; i++) {
          let element = {
            "name": this.namesForSecondTable[i],
            "uri": this.urisForSecondTable[i]
          };
          uris.push(element);
        }
      },


      /**
       * 效率计算表单相关
       */
      async calEfficiency(row) {

        let params = {
          "model_id": row.model_id,
          "gas_burn_loss": parseFloat(row.gas_burn_loss),
          "solid_burn_loss": parseInt(row.solid_burn_loss),
          "heat_loss": parseFloat(row.heat_loss),
          "ash_heat_loss": parseFloat(row.ash_heat_loss),
          "air_theory_enthalpy": parseFloat(row.air_theory_enthalpy),
          "low_calorific_value": parseFloat(row.low_calorific_value),
        };

        await getEfficiency(params).then(res => {
          if (res) {
            if (row.name === '实际') {
              this.currentOptimize = res.data.toFixed(2);
              console.log('实际效率', this.currentOptimize);
            } else {
              this.calEff = res.data.toFixed(2);
            }
          } else {
            this.calEff = '有参数未选择！';
          }
        });

        // this.drawEfficiencyChart();

      },

      /**
       * 模型表格相关
       */
      LoadModels() {

        getOptModelsInfo().then(res => {
          if (res) {
            let allModel = res.data;
            // console.log('allModel',res);
            let filterModel = [];
            // console.log('模型数据allModel', allModel);
            // console.log('锅炉状态this.boilerState', this.boilerState);

            for (let i = 0; i < this.boilerState.length; i++) {
              for (let j = 0; j < allModel.length; j++) {
                if (this.boilerState[i] === 1) {
                  if (allModel[j].boilerName.indexOf(i + 1) !== -1) {
                    filterModel.push(allModel[j]);
                  }
                }
              }
            }

            // console.log('filterModel', filterModel);
            this.optModelData = filterModel;
            // console.log('optModelData', this.optModelData);
            let modelData = filterModel;
            this.effFormModelIdOptions = [];
            for (let i = 0; i < modelData.length; i++) {
              let effFormModelId = {
                value: modelData[i].modelId,
                label: modelData[i].modelId
              };
              this.effFormModelIdOptions.push(effFormModelId);
            }
            this.getOptTree();
          } else {

          }
        })
      },

      //获取优化树
      getOptTree() {
        let getTreeParam = JSON.stringify({
          "depth": 4,
          "forward": true,
          "id": "6122e02dba3fd029798b2ebe"
        });
        getNodesByBrowsePath(this.getNodeToken, getTreeParam).then((res) => {
          if (res) {
            // console.log('优化树res', res);
            let tmp = res.data.result[0].children[1];
            tmp.children = tmp.children.filter(function (item) {
              return item.uri.substring(0, 8) === '/Project'
            }).sort((a, b) => a.name.localeCompare(b.name, 'en'));
            // console.log('过滤并排序优化树第一层', tmp.children);
            // console.log('this.optModelData',this.optModelData[0]);
            for (let i = 0; i < tmp.children.length; i++) {
              if (tmp.children[i].name == this.optModelData[0].boilerName) {
                let tmpWriteBack = tmp.children[i];
                tmpWriteBack.children = tmpWriteBack.children.filter(function (item) {
                  return item.uri.substring(0, 8) === '/Project'
                });
                // console.log('tmpWriteBack.children', tmpWriteBack.children);
                let nodesDict = {};
                for (let item of tmpWriteBack.children) {
                  nodesDict[item.name] = item;
                }
                // console.log('nodesDict', nodesDict);
                let tmpBoilerEffOpt = nodesDict['锅炉效率优化'];
                tmpBoilerEffOpt.children = tmpBoilerEffOpt.children.filter(function (item) {
                  return item.uri.substring(0, 8) === '/Project'
                });
                // console.log('tmpBoilerEffOpt.children', tmpBoilerEffOpt.children);
                let tmpBoilerEffOptDict = {};
                for (let item of tmpBoilerEffOpt.children) {
                  tmpBoilerEffOptDict[item.name] = item;
                }
                this.writeBackUri = tmpBoilerEffOptDict['实时效率'].uri;
                // console.log('tmpBoilerEffOptDict[\'实时效率\']',
                //   tmpBoilerEffOptDict['实时效率'], 'this.writeBackUri', this.writeBackUri);
                // console.log('tmpBoilerEffOptDict[\'关键参数\']', tmpBoilerEffOptDict['关键参数']);
                this.defaultPreUri = tmpBoilerEffOptDict['关键参数'].uri.split("/")[2];
                this.boilerChargeUri = tmpBoilerEffOptDict['锅炉负荷'].uri;
                // console.log('this.boilerChargeUri', this.boilerChargeUri);
              }
            }
            // this.LoadCurrentEff();
            //获取默认展示参数
            // this.getPresent();
          }
        });
      },
      //训练模型
      trainModel(row) {
        let param = {
          model_id: row.modelId
        };
        train(param).then((res) => {
          if (res) {

          }
        })
      },

      /**
       * 主调参数表单
       *
       */
      getOptEfficiency(optMainParams, optMainParamsRule) {

        let opt_main_paras = {
          "supplyFlow1": optMainParams.supplyFlow1,
          "supplyFlow2": optMainParams.supplyFlow2,
          "airVolume": optMainParams.airVolume
        };
        let params = {
          "model_id": this.effFormModelId,
          "opt_main_paras": opt_main_paras
        };
        getOwnOptimalEfficiency(params).then(res => {
          if (res) {
            if (res.data < 0 || res.data > 100) {
              this.ownOptEff = '所选锅炉已关闭';
            } else {
              this.ownOptEff = res.data.toFixed(2);
            }

          }
        })
      },
      /**
       * 一键优化
       *
       */
      async optimization(row) {
        // console.log('row', row);
        let writeBackUriParam = [];
        writeBackUriParam[0] = row.currentEfficiency;
        writeBackUriParam[0] = writeBackUriParam[0].substring(0, writeBackUriParam[0].length - 5);


        //TODO 后端返回模型时返回回写uri
        let
          writeBackUriParams = [
            "/Project_XCGLDSJFX/61507884ba3fd029798e5426",//1号锅炉实时效率
            "/Project_XCGLDSJFX/61507898ba3fd029798e543a",//2号锅炉实时效率
            "/Project_XCGLDSJFX/615078abba3fd029798e545a"//3号锅炉实时效率
          ];
        // let writeBackUriParam = [];
        // if (row.boilerName.indexOf("1") !== -1) {
        //   writeBackUriParam[0] = writeBackUriParams[0];
        // } else if (row.boilerName.indexOf("2") !== -1) {
        //   writeBackUriParam[0] = writeBackUriParams[1];
        // } else if (row.boilerName.indexOf("3") !== -1) {
        //   writeBackUriParam[0] = writeBackUriParams[2];
        // }
        // writeBackUriParam = JSON.stringify(writeBackUriParam);
        // console.log('writeBackUriParam', writeBackUriParam);
        queryCurrentRawValueByUri(writeBackUriParam).then((res) => {
          if (res) {

            this.beforeOptimize = res.data.result[0].v.toFixed(2);
          }
        });

        let param = {"model_id": row.modelId};
        await getOptimalEfficiency(param).then((res) => {
          this.targetOptimizeArray = [];
          this.transTarget = [];
          this.chartModelId = row.modelId;
          this.controlAim = [];
          this.controlParaName = [];
          this.controlCurrent = [];
          this.controlUri = [];
          if (res) {
            let optPara = res.data.control_para;
            this.optMainParams.supplyFlow1 = optPara[0].toFixed(2);
            this.optMainParams.supplyFlow2 = optPara[1].toFixed(2);
            this.optMainParams.airVolume = optPara[2].toFixed(2);

            //主调参数uri，用于柱状图获取实时值
            this.mainControl = res.data.control_para_uri;
            // console.log(' this.mainControl', this.mainControl);
            for (let i = 0; i < this.mainControl.length; i++) {
              this.controlParaName.push(this.mainControl[i].name);
              this.controlUri.push(this.mainControl[i].uri);
              this.controlAim.push(optPara[i].toFixed(2));
            }

            //环状图显示目标效率
            this.targetOptimize = res.data.efficiency.toFixed(2);
            var date = new Date().getTime();
            this.targetOptimizeArray.push(date);
            this.targetOptimizeArray.push(this.targetOptimize);
            for (let i = 0; i < this.controlParaName.length; i++) {
              this.targetOptimizeArray.push(this.controlParaName[i]);
              this.targetOptimizeArray.push(this.controlAim[i]);
            }
            this.transTarget.push(this.targetOptimizeArray);
            this.renderChart();
            //用于使雷达图以及柱状图显示
            this.optimized = true;
            this.valueShow = true;
            this.stateShow = true;
          }
        });

      },

      /**
       * 子组件向父组件传值
       */
      parentFn(value) {
        this.currentOptimize = value.v.toFixed(2);
      },

      /**
       * 柱状图 雷达图
       */
      renderChart() {
        //获取雷达图参数
        let uris = [];
        for (let i = 0; i < this.namesForSecondTable.length; i++) {
          let element = {
            "name": this.namesForSecondTable[i],
            "uri": this.urisForSecondTable[i]
          };
          uris.push(element);
        }
        let param = {
          "uris": uris
        };
        // console.log('param', param);
        // getOptimalEfficiency(param).then((res) => {
        //   this.controlAim = [];
        //   this.controlCurrent = [];
        //   this.controlParaName = [];
        //
        //   if (res) {
        //     this.beforeOptimize = this.currentOptimize;
        //     this.targetOptimize = res.data.optimal.toFixed(2);
        //     this.controlParas = res.data.control;
        //     for (let i in res.data.control) {
        //       let controlPara = res.data.control[i];
        //       this.controlParaName.push(i);
        //       this.controlAim.push(controlPara.aim);
        //       this.controlCurrent.push(controlPara.current);
        //     }
        //     this.optimized = true;
        //   }
        // });
      },

      /**
       * 右侧表格
       */
      async drawfData() {
        await this.getValues();
        this.currentParams = [];
        for (let i = 0; i < this.namesForSecondTable.length; i++) {
          let tmpCurrentParam;
          tmpCurrentParam = {
            uri: this.urisForSecondTable[i],
            currentValue: this.values[i],
            optimizationGoals: this.namesForSecondTable[i],
            unit: this.unitForSecondTable[i]
          };
          this.currentParams.push(tmpCurrentParam);
        }
      },
      async getValues() {
        await queryCurrentRawValueByUri(this.urisForSecondTable).then((res) => {
          if (res) {
            this.values = [];
            for (let i = 0; i < res.data.result.length; i++) {
              if (null == res.data.result[i]) {
                this.values.push(0);
              } else {
                this.values.push(res.data.result[i].v);
              }
              if (this.selectedRowName == '') {
                this.selectedRowName = this.namesForSecondTable[0];
                this.selectedRowUri = this.urisForSecondTable[0];
                this.currentRowUri = this.urisForSecondTable[0];
              }

            }
          }
        });
      },
      handleParamClick(currentParam) {
        this.selectedRowName = currentParam.optimizationGoals;
        this.selectedRowUri = currentParam.uri;
        this.currentRowUri = currentParam.uri;
      },


    }
  }
</script>

<style scoped>
  .middleContainer {
    margin-left: 15px;
  }

  .treeCard {
    margin-bottom: 15px;
  }

  .calCard {
    margin-bottom: 15px;
  }

  .modelCard {
    margin-bottom: 16px;
  }

  .ring-outer {
    margin-bottom: 15px;
  }

  .preCard {
    margin-bottom: 15px;
  }

  .rightContainer {
    margin-left: 15px;
  }

  .customer-page {
    background: #FFFFFF;
    box-shadow: 0 2px 4px 0 rgba(147, 157, 165, 0.48);
    text-align: left;
  }

  .customer-page-table {
    display: table;
    width: 100%;
  }

  .table-row.header {
    background: #F8F8F9;
    color: #515A6E;
    display: table-row;
    height: 40px;
  }

  .table-row {
    display: table-row;
  }

  .item-content {
    display: table-cell;
  }

  .table-row.header .item-content {
    font-weight: 600;
    color: #707485;
  }

  .table-row:not(:last-child) .item-content {
    border-bottom: 1px solid #979797;
  }

  .table-row .item-content {
    /*height: 60px;*/
    text-align: left;
    /*line-height: 60px;*/
    width: auto;
  }

  /*@media screen and (max-width: 500px) {*/

  /*  .customer-page-tabl {*/
  /*    display: inline;*/
  /*  }*/

  /*  .table-row {*/
  /*    border: 1px solid #ddd;*/
  /*    margin-bottom: 10px;*/
  /*    display: block;*/
  /*    border-bottom: 2px solid #ddd;*/
  /*  }*/

  /*  .table-row.header {*/
  /*    display: none;*/
  /*  }*/

  /*  .table-row .item-content {*/
  /*    display: block;*/
  /*    text-align: right;*/
  /*    font-size: 13px;*/
  /*    border-bottom: 1px dotted #ccc;*/
  /*    height: 50px;*/
  /*    line-height: 50px;*/
  /*    padding: 0 10px;*/
  /*  }*/

  /*  .table-row .item-content:last-child {*/
  /*    border-bottom: 0;*/
  /*  }*/

  /*  .table-row .item-content:before {*/
  /*    content: attr(data-label);*/
  /*    float: left;*/
  /*    text-transform: uppercase;*/
  /*    font-weight: bold;*/
  /*  }*/
  /*}*/

</style>
